package com.manong.utils;

import javax.servlet.http.HttpServletRequest;

public class IpAddressUtil {
    /**
     * 获取客户端的 IPv4 地址
     */
    public static String getClientIPv4(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        // 如果存在多个IP地址（如X-Forwarded-For），取第一个IP地址
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }
        // 提取 IPv4 地址
        return extractIPv4(ipAddress);
    }

    /**
     * 从 IP 地址中提取 IPv4 部分
     */
    private static String extractIPv4(String ipAddress) {
        if (ipAddress == null || ipAddress.isEmpty()) {
            return ipAddress;
        }
        // 检查是否是 IPv4 映射的 IPv6 地址（如 ::ffff:192.168.1.1）
        if (ipAddress.startsWith("::ffff:")) {
            return ipAddress.substring(7); // 提取 IPv4 部分
        }
        // 检查是否是纯 IPv4 地址
        if (ipAddress.contains(".")) {
            return ipAddress;
        }
        // 如果是纯 IPv6 地址，无法转换为 IPv4，返回 null
        return ipAddress;
    }
}
